//场景：
// const defaultSceneOrPrefab = "./assets/scenes/.yaml";
// const defaultSceneOrPrefab = "./assets/scenes/totalScene.yaml";
// const defaultSceneOrPrefab = "./assets/scenes/scene8.yaml";
const defaultSceneOrPrefab = "./assets/scenes/menu.yaml";
// const defaultSceneOrPrefab = "./assets/scenes/chooseMenu.yaml";
//const defaultSceneOrPrefab = "./assets/scenes/dialogscene1.yaml"
// const defaultSceneOrPrefab = "./assets/scenes/explain.yaml";
// const defaultSceneOrPrefab = "./assets/scenes/pause.yaml";
// const defaultSceneOrPrefab = "./assets/scenes/xjytest.yaml";

//预制体：
// const defaultSceneOrPrefab = "./assets/prefabs/block.yaml";
// const defaultSceneOrPrefab = "./assets/prefabs/Portal.yaml";
// const defaultSceneOrPrefab = "./assets/prefabs/Stone.yaml";
// const defaultSceneOrPrefab = "./assets/prefabs/BackGround.yaml";
// const defaultSceneOrPrefab = "./assets/prefabs/Role.yaml";
// const defaultSceneOrPrefab = "./assets/prefabs/animationTest.yaml"



const config = require("./config.json");
const { app, BrowserWindow, BrowserView, globalShortcut } = require("electron");
async function startupCompiler() {
  const { createServer } = require("vite");
  const server = await createServer({
    // 任何合法的用户配置选项，加上 `mode` 和 `configFile`
    configFile: false,
    root: __dirname,

    server: {
      port: 3000,
    },
  });
  await server.listen();

  server.printUrls();
}

let runtimeView;
let editorProcess;

async function startEditor() {

  const width =
    config.editor.hierarchy.width +
    config.editor.runtime.width +
    config.editor.inspector.width;
  const height =
    Math.max(
      config.editor.runtime.height,
      config.editor.hierarchy.height,
      config.editor.inspector.height
    ) + 300;
  function createWindow() {
    // const editorProcess = new BrowserWindow({
      editorProcess = new BrowserWindow({
      width: width,
      height: height+40,
      resizable: false,
      webPreferences: {
        nodeIntegration: true, //允许渲染进程使用Nodejs
        contextIsolation: false, //允许渲染进程使用Nodejs
      },
    });
    editorProcess.loadURL("http://localhost:3000/editor.html");
    runtimeView = new BrowserView({
      webPreferences: {
        webSecurity: true,
        contextIsolation: true,
        nodeIntegration: false,
        allowRunningInsecureContent: false,
      },
    });
    editorProcess.addBrowserView(runtimeView);
    runtimeView.setBounds({
      x: config.editor.hierarchy.width,
      y: 0,
      width: config.editor.runtime.width,
      height: config.editor.runtime.height,
    });
    const mode = "edit";
    runtimeView.webContents.loadURL(
      `http://localhost:3000/index.html?mode=${mode}&prefab=${encodeURIComponent(
        defaultSceneOrPrefab
      )}`
    );
    globalShortcut.register("Alt+B", function () {
      runtimeView.webContents.openDevTools();
    });
  }

  app.whenReady().then(() => {
    createWindow();
    app.on("activate", () => {
      if (BrowserWindow.getAllWindows().length === 0) createRuntimeProcess();
    });
  });

  app.on("window-all-closed", () => {
    if (process.platform !== "darwin") app.quit();
  });
}

function generateAssetsYaml() {
  const fs = require("fs");
  const imageFiles = fs.readdirSync("assets/images");
  const imageAssets = imageFiles
    .filter((item) => item.includes(".jpg") || item.includes(".png"))
    .map((item) => "./assets/images/" + item);

  const prefabFiles = fs.readdirSync("assets/prefabs");
  const prefabAssets = prefabFiles
    .filter((item) => item.includes(".yaml"))
    .map((item) => "./assets/prefabs/" + item);

  const animationFiles = fs.readdirSync("assets/animations");
  const animationAssets = animationFiles
    .filter((item) => item.includes(".jpg") || item.includes(".png"))
    .map((item) => "./assets/animations/" + item);

    
  const sceneFiles = fs.readdirSync("assets/scenes");
  const sceneAssets = sceneFiles
    .filter((item) => item.includes(".yaml"))
    .map((item) => "./assets/scenes/" + item);

  const content =
    "images:\n" +
    imageAssets.map((item) => "  - " + item).join("\n") +
    "\n" +
    "prefabs:\n" +
    prefabAssets.map((item) => "  - " + item).join("\n") +
    "\n" +
    "animations:\n" +
    animationAssets.map((item) => "  - " + item).join("\n")+
    "\n"+
    "scenes:\n" +
    sceneAssets.map((item) => "  - " + item).join("\n");
  fs.writeFileSync("./assets/assets.yaml", content, "utf-8");
}

async function startup() {
  generateAssetsYaml();
  new WebSocketProxy().start();
  await startupCompiler();
  await startEditor();
}

class WebSocketProxy {
  editorClient;
  runtimeClient;

  start() {
    const { Server } = require("ws");
    const wss = new Server({ port: 1234 });
    wss.on("connection", (client) => {
      client.on("message", (text) => {
        const message = JSON.parse(text);
        if (message.command === "login") {
          this.handleLogin(message, client);
        } else if (message.command === "changeMode") {
          this.handleChangeMode(message);
        } else {
          this.handleDispatchToOtherRendererProcess(message, text);
        }
      });
    });
  }

  handleChangeMode(message) {
    const mode = message.data;
    const url = `http://localhost:3000/index.html?mode=${mode}&prefab=${encodeURIComponent(
      defaultSceneOrPrefab
    )}`;
    if (mode === "play") {
      const player = new BrowserWindow({
        // width: 800,
        // height: 600 + 45,
        width: config.player.width,
        height: config.player.height + 30,
        autoHideMenuBar: true,
        resizable: false,
        webPreferences: {
          nodeIntegration: true, //允许渲染进程使用Nodejs
          contextIsolation: false, //允许渲染进程使用Nodejs
        },
      });
      player.loadURL(url);
      player.webContents.openDevTools();
    } else {
      runtimeView.webContents.loadURL(url);

      // if (mode === "preview") {
      //   // b.webContents.loadURL("http://www.baidu.com");
      //   debuggerView = new BrowserView();
      //   runtimeView.webContents.setDevToolsWebContents(
      //     debuggerView.webContents
      //   );
      //   editorProcess.addBrowserView(debuggerView);
      //   debuggerView.setBounds({
      //     x: config.editor.hierarchy.width + config.editor.runtime.width,
      //     y: 0,
      //     width: config.editor.inspector.width,
      //     height: config.editor.inspector.height,
      //   });
      //   runtimeView.webContents.openDevTools({ mode: "detach" });
      // } else {
      //   runtimeView.webContents.closeDevTools();
      //   editorProcess.removeBrowserView(debuggerView);
      //   debuggerView = null;
      // }
    }
  }

  handleLogin(data, client) {
    if (data.id === "editor") {
      this.editorClient = client;
    } else if (data.id === "runtime") {
      this.runtimeClient = client;
    }
    if (this.editorClient && this.runtimeClient) {
      const text = JSON.stringify({ command: "loginSuccess" });
      this.editorClient.send(text);
      this.runtimeClient.send(text);
    }
  }

  handleDispatchToOtherRendererProcess(data, text) {
    if (data.id === "editor") {
      this.runtimeClient.send(text);
    } else if (data.id === "runtime") {
      this.editorClient.send(text);
    }
  }
}

startup().catch((e) => {
  console.log(e);
});
